<?php

/**
 * User: Monjra
 * Date: 2020/12/11 10:10
 */

namespace app\admin\controller;

use think\Request;
use app\index\model\User;
use Illuminate\Support\Arr;
use app\admin\model\Service;
use think\Db;

class Examine extends Base
{
    public function index()
    {
        if (request()->isAjax()) {
            $input = request()->get();
            $limit = $input['pageSize'];
            $condition = ['status' => ['<>', User::STATUS_PASS]];

            if (isset($input['status'])) {
                $condition['status'] = $input['status'];
            }
            if (!empty($input['searchText'])) {
                $condition['name'] = ['like', '%' . $input['searchText'] . '%'];
            }

            $offset = ($input['pageNumber'] - 1) * $limit;
            $count = User::where($condition)->count();

            $result = User::field('id,nickname,name,sex,age,mobile')
                ->limit($offset, $limit)
                ->where($condition)
                ->select()
                ->map(function ($item) {
                    $item['operate'] = $this->makeBtn($item->id);
                    $item['sex'] = config('sex')[$item['sex']] ?? '';
                    return $item;
                });

            return json([
                'total' => $count,
                'rows' => $result->toArray()
            ]);
        }

        $this->assign('status', request()->get('status', ''));
        return $this->fetch();
    }
    private function makeBtn($id)
    {
        $operate = '<a href="' . url('examine/choose', ['id' => $id]) . '">';
        $operate .= '<button type="button" class="btn btn-primary btn-sm"><i class="fa fa-paste"></i>审核</button></a> ';
        $operate .= '<a href="' . url('examine/bind', ['id' => $id]) . '">';
        $operate .= '<button type="button" class="btn btn-danger btn-sm"><i class="fa fa-trash-o"></i>绑定顾客</button></a> ';
        $operate .= '<a href="' . url('examine/bindService', ['id' => $id]) . '">';
        $operate .= '<button type="button" class="btn btn-warning btn-sm"><i class="fa fa-user-plus"></i>绑定人员</button></a> ';
        $operate .= '<a href="' . url('users/addUser', ['id' => $id]) . '">';
        $operate .= '<button type="button" class="btn btn-info btn-sm"><i class="fa fa-user-plus"></i>新增人员</button></a> ';

        //$operate .= '<a href="' . url('groups/manageUser') . '">';
        //$operate .= '<button type="button" class="btn btn-info btn-sm"><i class="fa fa-user-plus"></i> 管理组员</button></a>';

        return $operate;
    }


    // 审核客户
    public function choose()
    {
        if (request()->isAjax()) {
            $param = input('post.');
            $id = $param['id'];
            $status = empty($param['status']) ? User::STATUS_NO_PASS : User::STATUS_PASS;
            $name = trim($param['name']);
            $param = Arr::only($param, ['service_id', 'department_id', 'market_id', 'shop_id']);
            if ($status == User::STATUS_PASS && 4 !== count(array_filter($param, fn ($v) => $v && is_numeric($v)))) {
                return json(['code' => -1, 'data' => '', 'msg' => '请设置完整的负责人']);
            }
            try {
                $param['status'] = $status;
                $param['name'] = $name;
                User::where('id', $id)->update($param);
            } catch (\Exception $e) {
                return json(['code' => -2, 'data' => '', 'msg' => $e->getMessage()]);
            }

            return json(['code' => 1, 'data' => '', 'msg' => '审核成功']);
        }

        $id = input('param.id/d');
        $info = db('users')->where('id', $id)->find();
        $kfs = Service::where('role', Service::ROLE_SERVICE)->column('user_name', 'id');
        $this->assign([
            'info' => $info,
            'kfs' => $kfs,
            'status' => config('kf_status')
        ]);
        return $this->fetch();
    }
    public function edit()
    {
        if (request()->isAjax()) {
            $param = input('post.');
            $id = $param['id'];
            //只更新文件时不检查负责客服
            if (request()->get('uploadFile') != 1) {
                $status = empty($param['status']) ? User::STATUS_NO_PASS : User::STATUS_PASS;
                $param['status'] = $status;
                $check_service = Arr::only($param, ['service_id', 'department_id', 'market_id', 'shop_id']);
                if (4 !== count(array_filter($check_service, fn ($v) => $v && is_numeric($v)))) {
                    return json(['code' => -1, 'data' => '', 'msg' => '请设置完整的负责人']);
                }
            }
            try {
                (new User)->allowField(true)->save($param, ['id' => $id]);
            } catch (\Exception $e) {
                return json(['code' => -2, 'data' => '', 'msg' => $e->getMessage()]);
            }

            return json(['code' => 1, 'data' => '', 'msg' => '修改成功']);
        }

        $id = input('param.id/d');
        $info = User::find($id);
        $kfs = Service::field(["CONCAT(service_name,'-', user_name)" => 'user_name', 'id', 'role', 'superior_id'])->select()->groupBy('role');
        $this->assign([
            'info' => $info,
            'service' => $kfs->get(Service::ROLE_SERVICE)->toArray(),
            'department' => $kfs->get(Service::ROLE_DEPARTMENT)->where('superior_id', $info->service_id)->toArray(),
            'market' => $kfs->get(Service::ROLE_MARKET)->where('superior_id', $info->department_id)->toArray(),
            'shop' => $kfs->get(Service::ROLE_SHOP)->where('superior_id', $info->market_id)->toArray(),
            'status' => config('kf_status')
        ]);
        return $this->fetch();
    }

    //绑定用户
    public function bind()
    {
        if (request()->isAjax()) {
            try {
                Db::startTrans();
                $id = request()->post('id');
                $target_user = User::find($id);
                $bind_id = request()->post('bind_id');
                if (!$bind_id) {
                    throw new \Exception('请选择要绑定的顾客');
                }
                // $openid = request()->post('openid');
                $bind_user = User::where('id', $bind_id)->find();
                $bind_user->openid = $target_user->openid;
                $bind_user->nickname = $target_user->nickname;
                if (!$bind_user->headimgurl) {
                    $bind_user->headimgurl = $target_user->headimgurl;
                }
                $target_user->delete();
                $bind_user->save();
                Db::commit();
                return ['code' => 0, 'msg' => '绑定成功', 'data' => url('admin/examine/edit', ['id' => $bind_id])];
            } catch (\Throwable $th) {
                Db::rollBack();
                return ['code' => -1, 'msg' => $th->getMessage()];
            }
        }


        $id = input('param.id/d');
        $info = User::find($id);
        $users = User::whereNull('ws_users.openid')->join('ws_services', 'ws_services.id = ws_users.shop_id')->column("CONCAT(ws_services.service_name, '-', ws_users.name)", 'ws_users.id');
        $this->assign([
            'info' => $info,
            'users' => $users,
            'status' => config('kf_status')
        ]);
        return $this->fetch();
    }

    public function bindService($id)
    {
        if ($this->request->isAjax()) {

            Db::startTrans();
            $id = request()->post('id');
            $target_user = User::find($id);
            $bind_id = request()->post('bind_id');
            if (!$bind_id) {
                throw new \Exception('请选择要绑定的顾客');
            }
            // $openid = request()->post('openid');
            $bind_user = Service::where('id', $bind_id)->find();
            $bind_user->openid = $target_user->openid;
            $bind_user->user_name = $target_user->name;
            if (!$bind_user->mobile) {
                $bind_user->mobile = $target_user->mobile;
            }
            if (!$bind_user->user_avatar) {
                $bind_user->user_avatar = $target_user->headimgurl;
            }
            $target_user->delete();
            $bind_user->save();
            Db::commit();
            return ['code' => 0, 'msg' => '绑定成功', 'data' => url('admin/users/editUser', ['id' => $bind_id])];
        }
        $info = User::find($id);
        $users = Service::whereNull('openid')->whereOr('openid', '')->column("CONCAT(service_name,'-', user_name)", 'id');
        $this->assign([
            'info' => $info,
            'users' => $users,
            'status' => config('kf_status')
        ]);
        return $this->fetch();
    }

    public function getUnBindUser()
    {
        if (request()->isAjax()) {
            //
            return User::whereNull('openid')->column('name', 'id');
        }
    }
}
